package com.wnhz.work.jy.activity;

import android.Manifest;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.Editable;
import android.text.InputFilter;
import android.text.TextWatcher;
import android.util.Log;
import android.view.View;
import android.view.Window;
import android.widget.EditText;
import android.widget.TextView;

import com.wnhz.work.jy.BaseActivity;
import com.wnhz.work.jy.MyApplication;
import com.wnhz.work.jy.R;
import com.wnhz.work.jy.adapter.MyPublicTaskRecycleAdapter;
import com.wnhz.work.jy.utils.ConfigUtil;
import com.wnhz.work.jy.utils.xutils3.MyCallBack;
import com.wnhz.work.jy.utils.xutils3.XUtil;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import me.nereo.multi_image_selector.MultiImageSelector;
import me.nereo.multi_image_selector.MultiImageSelectorActivity;

/**
 * ---评价
 */
public class EvaluateActivity extends BaseActivity implements View.OnClickListener, View.OnLongClickListener {
    private static final String TAG = "EvaluateActivity";
    private static final int MY_PERMISSIONS_REQUEST_CALL_PHONE = 963;
    private TextView title;
    private final int FROM_CAMERA_CODE = 101;// 调用相机更改背景图片的请求code
    private final int FROM_ALBUM_CODE = 102;// 调用相册更改背景图片的请求code
    private EditText et_content;
    private TextView tv_numb_max;

    private RecyclerView recyclerView;
    private MyPublicTaskRecycleAdapter mTaskImgAdapter;
    private List<Integer> imageRes = new ArrayList<>();
    private ArrayList<String> imagePaths = new ArrayList<>();
    private String order_detail_id;
    private String content;
    private String goodsid;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_evaluate);
        order_detail_id = getIntent().getStringExtra("order_detail_id");
        goodsid = getIntent().getStringExtra("goodsid");
        initData();
        initView();
    }

    private void initData() {
        imagePaths.add(R.mipmap.ic_addpicture + "");
    }

    private void initView() {
        title = (TextView) findViewById(R.id.view_main_middle_title);
        title.setText("发表评价");
        findViewById(R.id.btn_main_left).setOnClickListener(this);
        findViewById(R.id.tv_pics_clear).setOnClickListener(this);
        findViewById(R.id.tv_publish_task).setOnClickListener(this);

        recyclerView = (RecyclerView) findViewById(R.id.publish_task_recyclerView);
        et_content = (EditText) findViewById(R.id.et_content);
        tv_numb_max = (TextView) findViewById(R.id.tv_numb_max);

        et_content.setFilters(new InputFilter[]{new InputFilter.LengthFilter(201)});//设置最多字数
        et_content.addTextChangedListener(mTextWatcher);

        LinearLayoutManager manager = new LinearLayoutManager(this);
        manager.setOrientation(LinearLayoutManager.HORIZONTAL);
        recyclerView.setLayoutManager(manager);

        mTaskImgAdapter = new MyPublicTaskRecycleAdapter(this, imageRes, imagePaths, this, this);

        recyclerView.setAdapter(mTaskImgAdapter);

    }

    private View v;

    @Override
    public void onClick(View v) {
        Intent intent;
        switch (v.getId()) {
            case R.id.btn_main_left:
                finish();
                break;

            case R.id.item_publishTask_image:
                if (ContextCompat.checkSelfPermission(this,
                        Manifest.permission.READ_EXTERNAL_STORAGE)
                        != PackageManager.PERMISSION_GRANTED) {
                    ActivityCompat.requestPermissions(this,
                            new String[]{Manifest.permission.READ_EXTERNAL_STORAGE},
                            MY_PERMISSIONS_REQUEST_CALL_PHONE);
                    this.v = v;
                } else {
                    getImg(v);
                }


                break;

            //清除图片
            case R.id.tv_pics_clear:

                imagePaths.clear();
                imagePaths.add(R.mipmap.ic_addpicture + "");
                mTaskImgAdapter.notifyDataSetChanged();
//                tv_pic_num.setText("0/6");

                break;

            //发布评论
            case R.id.tv_publish_task:
                content = et_content.getText().toString();
                if ("".equals(content)) {
                    MyToast("请输入评论内容");
                } else {
                    updatedisc();
                }

                break;

            default:
                break;
        }

    }

    private void getImg(View v) {
        Intent intent;
        Integer index = (Integer) v.getTag();
        if (index == imagePaths.size() - 1) {
            if (imagePaths.size() >= 7) {
                MyToast("最多选择6张图片");
                return;
            }
            intent = new Intent(EvaluateActivity.this, MultiImageSelectorActivity.class);
            // 是否显示调用相机拍照
            intent.putExtra(MultiImageSelectorActivity.EXTRA_SHOW_CAMERA, true);
            // 最大图片选择数量
            intent.putExtra(MultiImageSelectorActivity.EXTRA_SELECT_COUNT, 7 - imagePaths.size());
            // 设置模式 (支持 单选/MultiImageSelectorActivity.MODE_SINGLE 或者 多选/MultiImageSelectorActivity.MODE_MULTI)
            intent.putExtra(MultiImageSelectorActivity.EXTRA_SELECT_MODE, MultiImageSelectorActivity.MODE_MULTI);
            startActivityForResult(intent, FROM_ALBUM_CODE);
        } else {
            ArrayList<String> paths = new ArrayList<>();
            paths.addAll(imagePaths);
            paths.remove(paths.get(paths.size() - 1));
            intent = new Intent(EvaluateActivity.this, ShowImageDetail.class);
            intent.putStringArrayListExtra("paths", paths);
            intent.putExtra("index", index);
            startActivity(intent);
        }
    }

    @Override
    public boolean onLongClick(View v) {
        final Integer index = (Integer) v.getTag();

        System.out.println("index:===" + index);
        /**
         这里使用了 android.support.v7.app.AlertDialog.Builder
         可以直接在头部写 import android.support.v7.app.AlertDialog
         那么下面就可以写成 AlertDialog.Builder
         */
        android.support.v7.app.AlertDialog.Builder builder = new android.support.v7.app.AlertDialog.Builder(this);
        builder.setMessage("是否确认删除？");
        builder.setNegativeButton("取消", null);
        builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                imagePaths.remove(imagePaths.get(index));
                mTaskImgAdapter.notifyDataSetChanged();
//                tv_pic_num.setText((imagePaths.size() - 1) + "/6");
            }
        });
        builder.show();


        return true;
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        switch (requestCode) {

            //相册
            case FROM_ALBUM_CODE:
                if (resultCode == RESULT_OK) {
                    if (null != data) {
//                        imagePaths.clear();
//                        imagePaths.add(R.mipmap.ic_tupiantianjia3x + "");

//                        List<String> list = data.getStringArrayListExtra("pick");

                        List<String> list = data.getStringArrayListExtra(MultiImageSelector.EXTRA_RESULT);
                        System.out.println("========：" + list.size());
                        if (imagePaths.size() < 7) {

                            for (int i = 0; i < list.size(); i++) {
                                System.out.println("选中的路径：" + list.get(i));

                                imagePaths.add(0, list.get(i));
                            }
                        } else {
                            MyToast("无法添加更多图片");
                        }
//                        tv_pic_num.setText((imagePaths.size() - 1) + "/6");

                        mTaskImgAdapter.notifyDataSetChanged();

                    }
                }
                break;

            default:
                break;
        }
    }

    TextWatcher mTextWatcher = new TextWatcher() {
        private CharSequence temp;
        private int editStart;
        private int editEnd;

        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {
            // TODO Auto-generated method stub
            temp = s;
        }

        @Override
        public void beforeTextChanged(CharSequence s, int start, int count,
                                      int after) {
            // TODO Auto-generated method stub
//          mTextView.setText(s);//将输入的内容实时显示
        }

        @Override
        public void afterTextChanged(Editable s) {
            // TODO Auto-generated method stub
            editStart = et_content.getSelectionStart();
            editEnd = et_content.getSelectionEnd();
            tv_numb_max.setText(temp.length() + "/200");
            if (temp.length() > 200) {
                MyToast("你输入的字数已经超过了限制");
                s.delete(editStart - 1, editEnd);
                int tempSelection = editStart;
                et_content.setText(s);
                et_content.setSelection(tempSelection);
            }
        }
    };


    private void updatedisc() {
        Map<String, Object> map = new HashMap<>();

        map.put("userId", MyApplication.getInstance().userBean.getUserId());
        map.put("content", content);
        map.put("goodsid", goodsid);
        map.put("order_detail_id", order_detail_id);
        for (int i = 0; i < imagePaths.size() - 1; i++) {
            map.put("img" + i, new File(imagePaths.get(i)));
        }
        showDialog();
        XUtil.Post(ConfigUtil.UPDATEDISC, map, new MyCallBack<String>() {
            @Override
            public void onSuccess(String result) {
                super.onSuccess(result);
                Log.e(TAG, "onSuccess: " + result);
                try {
                    JSONObject jsonObject = new JSONObject(result);
                    String re = jsonObject.optString("result");
                    String info = jsonObject.optString("info");
                    MyToast(info);
                    if ("1".equals(re)) {
                        finish();
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onFinished() {
                super.onFinished();
                closeDialog();
            }
        });
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {

        if (requestCode == MY_PERMISSIONS_REQUEST_CALL_PHONE) {
            if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                getImg(v);
            }
            return;
        }
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
    }
}
